package com.pinoc.Test;

import cn.hutool.core.thread.ThreadFactoryBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author pinoc
 * @date 2024/2/1
 */
public class CommonAsyncTaskManager {

	private ExecutorService commonThreadPoolExecutor;

	public CommonAsyncTaskManager(ExecutorService commonThreadPoolExecutor) {
		this.commonThreadPoolExecutor = commonThreadPoolExecutor;
	}

	public  <T> List<T> executeTasks(List<Callable<T>> tasks) throws InterruptedException {
		List<T> resultList = new ArrayList<>(tasks.size());
		CountDownLatch countDownLatch = new CountDownLatch(tasks.size());
		List<Future<T>> futureList = new ArrayList<>(tasks.size());
		for (Callable<T> task : tasks) {
			Future<T> submit = commonThreadPoolExecutor.submit(() -> {
				try {
					return task.call();
				} finally {
					countDownLatch.countDown();
				}
			});
			futureList.add(submit);
		}
		countDownLatch.await();
		try {
			for (Future<T> f : futureList) {
				T result = f.get();
				resultList.add(result);
			}
		}  catch (Exception e) {
			e.printStackTrace();
		}
		return resultList;
	}

	public Integer printSomething() {
		Integer count = 0;
		System.out.println("123");
		return count;
	}

	public static void main(String[] args) {
		ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 60, TimeUnit.SECONDS,
				new LinkedBlockingDeque<>(200),
				new ThreadFactoryBuilder().setNamePrefix("common-thread-pool-%d").build(),
				new ThreadPoolExecutor.CallerRunsPolicy()
		);
		CommonAsyncTaskManager commonAsyncTaskManager = new CommonAsyncTaskManager(threadPoolExecutor);
		List<Callable<Integer>> tasks = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			tasks.add(commonAsyncTaskManager::printSomething);
		}
		try {
			commonAsyncTaskManager.executeTasks(tasks);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
